import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../resources/kq_pad_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_pad_divider.dart';
import '../textFiled/kq_textfiled.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 输入组件
///
/// [ItemType.edit]
///
/// @author 周卓
///
/// 结合 KqPadFormEntity 使用
class KqPadEditItemView extends StatefulWidget {
  /// 通用属性
  final KqPadFormEntity entity;

  /// 输入控件或选择控件的左侧控件
  final Widget Function(KqPadFormEntity entity)? customLeftView;

  /// 输入控件或选择控件或自定义控件的右侧控件
  final Widget Function(KqPadFormEntity entity)? customRightView;

  /// 自定义控件的底部控件
  final Widget Function(KqPadFormEntity entity)? customBottomView;

  /// 输入变化回调
  final ValueChanged<String>? onChanged;

  /// 焦点变化
  final Function(bool hasFocus)? onFocusChanged;

  const KqPadEditItemView(
      {Key? key,
      required this.entity,
      this.customLeftView,
      this.customRightView,
      this.customBottomView,
      this.onChanged,
      this.onFocusChanged})
      : super(key: key);

  @override
  KqPadEditItemViewState createState() => KqPadEditItemViewState();
}

class KqPadEditItemViewState extends State<KqPadEditItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;

    if (widget.entity.controller != null &&
        widget.entity.valueForShow != null) {
      TextFiledUtil.setValue(
          widget.entity.controller!, widget.entity.valueForShow!);
    }

    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ?? KqPadThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          Container(
            color: bgColor,
            child: Row(
              crossAxisAlignment: widget.entity.multiline
                  ? CrossAxisAlignment.baseline
                  : CrossAxisAlignment.center,
              textBaseline:
                  widget.entity.multiline ? TextBaseline.alphabetic : null,
              children: <Widget>[
                KqPadVerticalDivider(
                  height: 18.r,
                  color: KqPadThemeColors.bgF0,
                ),

                Container(
                  color: KqPadThemeColors.bgFA,
                  height: 18.r,
                  width: 60.r,
                  padding: EdgeInsets.symmetric(horizontal: 6.r),
                  alignment: Alignment.centerRight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      /// 左边自定义控件
                      /// 自定义布局，来自实体类
                      widget.entity.customLeftView != null
                          ? widget.entity.customLeftView!(widget.entity)
                          : Container(),

                      /// 自定义布局，来自控件
                      widget.customLeftView != null
                          ? widget.customLeftView!(widget.entity)
                          : Container(),

                      LimitedBox(
                        maxWidth: 48.r,
                        child: Text(
                          widget.entity.title,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          textAlign: TextAlign.end,
                          style: widget.entity.titleStyle ??
                              TextStyle(
                                  fontSize: KqPadThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .titleFontSize ??
                                      6.sp,
                                  color: widget.entity.titleColor ??
                                      KqPadThemeColors.text26),
                        ),
                      ),
                    ],
                  ),
                ),

                KqPadVerticalDivider(
                  height: 18.r,
                  color: KqPadThemeColors.bgF0,
                ),

                Expanded(
                  /// 输入框
                  child: Row(
                    children: [
                      SizedBox(
                        width: 6.r,
                      ),
                      Expanded(
                        child: KqPadTextFiled(
                          multiline: widget.entity.multiline,
                          maxLines: widget.entity.maxLines,
                          inputType: widget.entity.inputType,
                          editable: widget.entity.isEditable(),
                          forceShowPlaceHolder:
                              widget.entity.forceShowPlaceHolder,
                          focusNode: widget.entity.focusNode,
                          controller: widget.entity.controller,
                          textColor: widget.entity.contentColor,
                          textInputAction: widget.entity.textInputAction,
                          fontSize: KqPadThemeManager.instance
                              .getConfig()
                              .formConfig
                              .contentFontSize,
                          enableClearButton: widget.entity.enableClearButton,
                          textAlign: TextAlign.start,
                          newValue: widget.entity.valueForShow ?? '',
                          placeHolder: widget.entity.hint,
                          maxCharCount: widget.entity.maxCharCount,
                          onSubmitted: widget.entity.onSubmitted,
                          inputFormatters: widget.entity.inputFormatters,
                          onFocusChanged: (hasFocus) {
                            widget.entity.onFocusChanged?.call(hasFocus);
                            widget.onFocusChanged?.call(hasFocus);
                          },
                          onMonitor: (str) {
                            widget.entity.onMonitor?.call(widget.entity, str);
                          },
                          onChanged: (text) {
                            widget.entity.valueForShow = text;
                            widget.entity.valueForSubmit = text;
                            widget.entity.onChanged?.call(text);
                            widget.onChanged?.call(text);
                          },
                        ),
                      ),
                    ],
                  ),
                ),

                /// 单位
                Visibility(
                  visible: widget.entity.unit.isNotNullOrEmpty,
                  child: Container(
                      padding: EdgeInsets.only(
                        left: widget.entity.isEditable() ? 6.r : 2.r,
                      ),
                      child: Text(
                        widget.entity.unit ?? "",
                        style: TextStyle(
                          color: widget.entity.unitColor ??
                              KqPadThemeColors.text26,
                          fontSize: KqPadThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .unitFontSize ??
                              6.sp,
                        ),
                      )),
                ),

                /// 自定义布局，来自实体类
                widget.entity.customRightView != null
                    ? widget.entity.customRightView!(widget.entity)
                    : Container(),

                /// 自定义布局，来自控件
                widget.customRightView != null
                    ? widget.customRightView!(widget.entity)
                    : Container(),

                SizedBox(
                  width: 6.r,
                ),

                KqPadVerticalDivider(
                  height: 18.r,
                  color: KqPadThemeColors.bgF0,
                ),
              ],
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 自定义控件，来自控件
          widget.customBottomView != null
              ? widget.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.hideDivider,
              child: const KqPadDivider(
                color: KqPadThemeColors.bgF0,
              ))
        ],
      ),
    );
  }
}
